package com.acme.bankapp.service.bank;

import java.io.*;
import java.util.regex.*;

import com.acme.bankapp.domain.account.*;
import com.acme.bankapp.domain.bank.*;
import com.acme.exceptions.ClientDuplicateException;
import com.acme.exceptions.ClientNotExistException;
import com.acme.exceptions.InjuredFileException;

public class BankDataLoader {
	
	/**
	 * Loads a file which contains data feed in the following format: <br>
	 * accounttype=c|s;balance=100;overdraft=50;name=John;gender=m|f;
	 * 
	 * @param bank
	 * @param path
	 * @throws IOException 
	 * @throws InjuredFileException 
	 * @throws ClientNotExistException 
	 * @throws ClientDuplicateException 
	 * @throws NumberFormatException 
	 */
	public void load(final Bank bank, final String path) throws IOException, InjuredFileException, NumberFormatException, ClientDuplicateException, ClientNotExistException {
		
		FileInputStream fstream = new FileInputStream(path);
		DataInputStream in = new DataInputStream(fstream);
		BufferedReader br = new BufferedReader(new InputStreamReader(in));
		String temp;
		String regLine = "^accounttype=([cs]);balance=([-+]?[0-9]*\\.?[0-9]*);overdraft=([-+]?[0-9]*\\.?[0-9]*);name=(\\w+);gender=([fm]);$";
		System.out.println(regLine);
		Account account;
		Gender gender;
		while((temp = br.readLine()) != null) {
			Pattern pattern = Pattern.compile(regLine);
			Matcher matcher = pattern.matcher(temp);
			while(matcher.find()) {
				if (matcher.group(1).equals("c")) {
					account = new CheckingAccount(Double.parseDouble(matcher.group(2)),Double.parseDouble(matcher.group(3)));
				} else {
					account = new SavingAccount(Double.parseDouble(matcher.group(2)));	
				}
				
				if (matcher.group(matcher.groupCount()) == "f") {
					gender = Gender.FEMALE;
				} else {
					gender = Gender.MALE;
				}
				
				bank.addClient(new Client(account,matcher.group(4),gender));
			}
		}
		br.close();
		in.close();
		fstream.close();
	}
}
